package servlet;

import entity.ClassGrade;
import service.ClassGradeService;
import service.ClassGradeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ClassAddServlet",urlPatterns = "ClassAddServlet")
public class ClassGradeAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码方式，解决中文乱码的问题
        response.setContentType("text/html; charset=utf-8");
        //获取请求中的班级信息并打印出来
        String flag = request.getParameter("flag");
        String className = request.getParameter("className");
        String gradeName = request.getParameter("gradeName");
        String leaderName = request.getParameter("leaderName");
        String classSlogan = request.getParameter("classSlogan");
        String classPeoples = request.getParameter("classPeoples");
        //打包数据后通过Service层实现对应的功能
        ClassGradeService classGradeService = new ClassGradeServiceImpl();
        // 根据隐藏域的结果分别实现增加和修改的功能
        int res = 0;
        ClassGrade classGrade = null;
        if ("add".equals(flag)) {
            classGrade  = new ClassGrade(className, gradeName, leaderName, classSlogan, (Integer.parseInt(classPeoples)));
            res = classGradeService.classGradeModifyService(classGrade);
        } else {
            classGrade = new ClassGrade(Integer.parseInt(flag), className, gradeName, leaderName, classSlogan, (Integer.parseInt(classPeoples)));
            res = classGradeService.classGradeModifyService(classGrade);
            System.out.println("修改数据的结果为：" + res);
        }
        // 3.通过输出流向前台页面展示处理结果，然后重新请求一次数据
        PrintWriter writer = response.getWriter();
        // 获取模块名称
        String contextPath = this.getServletContext().getContextPath();
        if(0 != res) {
            writer.print("管理班级信息成功！");
        }else{
            writer.print("管理班级信息失败！");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
